// lib/services/book_chapter_repository.dart
import 'package:ai_desktop_eidtor/util/string_util.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
import 'hive_models.dart';

class BookChapterRepository {
  static String _bookBox = 'books_box';
  static String _chapterBox = 'chapters_box';

  late Box<BookModel> _books;
  late Box<ChapterModel> _chapters;

  static final BookChapterRepository _instance =
      BookChapterRepository._internal();

  factory BookChapterRepository() => _instance;

  BookChapterRepository._internal();

  /// 初始化 Hive
  static Future<void> initializeHive() async {
    _bookBox += "_${StringUtil.userModel.userName}";
    _chapterBox += "_${StringUtil.userModel.userName}";
    final appDocumentDir = await getApplicationDocumentsDirectory();
    Hive.init(appDocumentDir.path);
  }

  /// 初始化数据库
  Future<void> init() async {
    // 注册适配器
    if (!Hive.isAdapterRegistered(1)) {
      Hive.registerAdapter(BookModelAdapter());
    }
    if (!Hive.isAdapterRegistered(2)) {
      Hive.registerAdapter(ChapterModelAdapter());
    }

    _books = await Hive.openBox<BookModel>(_bookBox);
    _chapters = await Hive.openBox<ChapterModel>(_chapterBox);
  }

  // ================ 书籍操作 ================

  /// 添加书籍
  Future<void> addBook(BookModel book) async {
    await _books.put(book.id, book);
  }

  /// 批量添加书籍
  Future<void> addBooks(List<BookModel> books) async {
    for (final book in books) {
      await _books.put(book.id, book);
    }
  }

  /// 获取所有书籍
  List<BookModel> getAllBooks() {
    return _books.values.toList()
      ..sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
  }

  /// 根据ID获取书籍
  BookModel? getBookById(String bookId) {
    return _books.get(bookId);
  }

  /// 更新书籍
  Future<void> updateBook(String bookId, BookModel updatedBook) async {
    final existingBook = _books.get(bookId);
    if (existingBook != null) {
      await _books.put(bookId, updatedBook);
    }
  }

  /// 部分更新书籍字段
  Future<void> partialUpdateBook({
    required String bookId,
    String? title,
    String? author,
    String? coverImage,
    String? description,
  }) async {
    final book = _books.get(bookId);
    if (book != null) {
      final updatedBook = BookModel(
        id: book.id,
        title: title ?? book.title,
        author: author ?? book.author,
        coverImage: coverImage ?? book.coverImage,
        description: description ?? book.description,
        createdAt: book.createdAt,
        sortOrder: book.sortOrder,
      );
      await _books.put(bookId, updatedBook);
    }
  }

  /// 删除书籍（同时删除相关章节）
  Future<void> deleteBook(String bookId) async {
    // 删除书籍
    await _books.delete(bookId);

    // 删除该书籍的所有章节
    final chaptersToDelete = _chapters.values
        .where((chapter) => chapter.bookId == bookId)
        .map((chapter) => chapter.id)
        .toList();

    for (final chapterId in chaptersToDelete) {
      await _chapters.delete(chapterId);
    }
  }

  /// 搜索书籍
  List<BookModel> searchBooks(String keyword) {
    if (keyword.isEmpty) return getAllBooks();

    final lowerKeyword = keyword.toLowerCase();
    return _books.values
        .where(
          (book) =>
              book.title.toLowerCase().contains(lowerKeyword) ||
              book.author.toLowerCase().contains(lowerKeyword) ||
              (book.description?.toLowerCase().contains(lowerKeyword) ?? false),
        )
        .toList();
  }

  // ================ 章节操作 ================

  /// 添加章节
  Future<void> addChapter(ChapterModel chapter) async {
    await _chapters.put(chapter.id, chapter);
  }

  /// 批量添加章节
  Future<void> addChapters(List<ChapterModel> chapters) async {
    for (final chapter in chapters) {
      await _chapters.put(chapter.id, chapter);
    }
  }

  /// 获取书籍的所有章节
  List<ChapterModel> getChaptersByBook(String bookId) {
    return _chapters.values
        .where((chapter) => chapter.bookId == bookId)
        .toList()
      ..sort((a, b) => a.chapterNumber.compareTo(b.chapterNumber));
  }

  /// 根据ID获取章节
  ChapterModel? getChapterById(String chapterId) {
    return _chapters.get(chapterId);
  }

  /// 更新章节内容
  Future<void> updateChapterContent({
    required String chapterId,
    required String content,
    String? title,
  }) async {
    final chapter = _chapters.get(chapterId);
    if (chapter != null) {
      final updatedChapter = ChapterModel(
        id: chapter.id,
        bookId: chapter.bookId,
        title: title ?? chapter.title,
        content: content,
        chapterNumber: chapter.chapterNumber,
        createdAt: chapter.createdAt,
        isRead: chapter.isRead,
      );
      await _chapters.put(chapterId, updatedChapter);
    }
  }

  /// 更新章节
  Future<void> updateChapter(
    String chapterId,
    ChapterModel updatedChapter,
  ) async {
    final existingChapter = _chapters.get(chapterId);
    if (existingChapter != null) {
      await _chapters.put(chapterId, updatedChapter);
    }
  }

  /// 删除章节
  Future<void> deleteChapter(String chapterId) async {
    await _chapters.delete(chapterId);
  }

  /// 删除书籍的所有章节
  Future<void> deleteChaptersByBook(String bookId) async {
    final chaptersToDelete = _chapters.values
        .where((chapter) => chapter.bookId == bookId)
        .map((chapter) => chapter.id)
        .toList();

    for (final chapterId in chaptersToDelete) {
      await _chapters.delete(chapterId);
    }
  }

  /// 标记章节为已读/未读
  Future<void> toggleChapterReadStatus(String chapterId) async {
    final chapter = _chapters.get(chapterId);
    if (chapter != null) {
      final updatedChapter = ChapterModel(
        id: chapter.id,
        bookId: chapter.bookId,
        title: chapter.title,
        content: chapter.content,
        chapterNumber: chapter.chapterNumber,
        createdAt: chapter.createdAt,
        isRead: !chapter.isRead,
      );
      await _chapters.put(chapterId, updatedChapter);
    }
  }

  /// 获取书籍统计信息
  Map<String, dynamic> getBookStatistics(String bookId) {
    final chapters = getChaptersByBook(bookId);
    final totalChapters = chapters.length;
    final readChapters = chapters.where((c) => c.isRead).length;
    final totalWords = chapters.fold(
      0,
      (sum, chapter) => sum + chapter.wordCount,
    );

    return {
      'totalChapters': totalChapters,
      'readChapters': readChapters,
      'readingProgress': totalChapters > 0
          ? (readChapters / totalChapters)
          : 0.0,
      'totalWords': totalWords,
      'averageWords': totalChapters > 0
          ? (totalWords / totalChapters).round()
          : 0,
    };
  }

  /// 清空所有数据
  Future<void> clearAllData() async {
    await _books.clear();
    await _chapters.clear();
  }

  /// 关闭数据库
  Future<void> close() async {
    await _books.close();
    await _chapters.close();
  }
}
